package com.cass.common;

import com.cass.uilts.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("Authorization");

        // 检查token是否为空
        if (token == null || !token.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false; // 如果token无效，则返回401 Unauthorized状态码
        }

        // 去掉 Bearer 前缀
        token = token.substring(7);

        // 验证token
        if (!JwtUtil.verify(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false; // 如果token验证失败，则返回401 Unauthorized状态码
        }

        // 如果token有效，继续处理请求
        return true;
    }
}
